package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author : Sonic
 * @version : 1.0
 * @createTime : 2024-12-22  22:56
 * @description :
 */

public class SimpleRedisLock implements ILock {

    // 锁的key
    private String name;
    private StringRedisTemplate stringRedisTemplate;
    private static final String KEY_PREFIX = "lock:";
    // 锁的标识，防止错删锁
    private static final String ID_PREFIX = UUID.randomUUID(true).toString() + "-";
    // DefaultRedisScript是一个实现类，泛型是返回值类型Long
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        // 设定脚本位置,new ClassPathResource会自动取resources下面找文件
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        // 设定返回值类型
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * @param: [timeoutSec]
     * @return: boolean
     * @description: 尝试获取锁
     **/
    @Override
    public boolean tryLock(long timeoutSec) {
        long threadID = Thread.currentThread().getId();
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, ID_PREFIX + threadID, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(flag);
    }

    /**
     * @param: []
     * @return: void
     * @description: 释放锁
     **/
    @Override
    public void unLock() {
        // 利用lua脚本实现redis的原子操作
        String threadID = ID_PREFIX + Thread.currentThread().getId();
        // UNLOCK_SCRIPT是一个类，需要读取文件获取
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                threadID);
    }
    // @Override
    // public void unLock() {
    //     String threadID =ID_PREFIX + Thread.currentThread().getId();
    //     String threadTAG = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
    //     // 问题: 判断操作和释放操作不是一个原子操作
    //     if (threadID.equals(threadTAG)) {
    //         // 若查询得到的线程标识 与 当前线程 一致就释放锁
    //         stringRedisTemplate.delete(KEY_PREFIX + name);
    //     }
    // }
}
